Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

TreeSet → Java TreeSet

TreeSet

Java TreeSet

TreeSets

TreeSet is an ordered Set implementation that maintains elements in ascending natural order. It uses a self-balancing binary search tree (like a red-black tree) for efficient storage and retrieval. This allows for fast searching, sorting, and retrieval of elements in their natural order.

Characteristics of TreeSets

Ordering: Elements are always stored in their natural order. This means the objects themselves need to be comparable (implement the Comparable interface). Uniqueness: Like HashSet, TreeSets don't allow duplicate elements. Performance: TreeSets offer efficient average logarithmic time (O(log n)) complexity for most operations (add, remove, search) due to the underlying tree structure. Custom Ordering: You can optionally define a custom comparator while creating a TreeSet to sort elements based on a different criteria than their natural order.

Declaring and Initializing TreeSets

Import
TreeSet import syntax import java.util.TreeSet;
This line imports the TreeSet class from the java.util package.
Declaration
Declaring TreeSet TreeSet<DataType> mySet;
This declares a variable named mySet of type TreeSet. The <DataType> placeholder specifies the type of elements the set will hold. This type must implement the Comparable interface for natural ordering.
Initialization Default constructor
Create an empty TreeSet mySet = new TreeSet<DataType>();
This creates an empty TreeSet that will use the natural ordering of the element type.
Adding elements during creation (Java 7+)
Create a TreeSet with initial elements TreeSet<String> months = new TreeSet<String>(); months.add("January"); months.add("February"); months.add("March");
This creates a TreeSet and adds initial elements while constructing it.

Common TreeSet Methods

first(): Returns the first (smallest) element in the set. ⮚last(): Returns the last (largest) element in the set. ⮚ceiling(element): Returns the least element in the set which is greater than or equal to the given element. ⮚floor(element): Returns the greatest element in the set which is less than or equal to the given element. ⮚comparator(): Returns the comparator used to order the elements (null for natural order).

Examples of TreeSet implementation

1. Strings (Natural Ordering)
Treeset example in java-natural sorting import java.util.TreeSet; public class Main { public static void main(String[] args) { TreeSet<String> names = new TreeSet<>(); names.add("Sathish"); names.add("Jaffer"); names.add("Joseph"); for (String name : names) { System.out.println(name); } } }

Output

Jaffer Joseph Sathish
This code creates a TreeSet named names that stores strings. Since String implements Comparable, elements are sorted based on their natural ordering (alphabetical order in this case).
2. Integers (Natural Ordering)
Treeset example with integers in java import java.util.TreeSet; public class Main { public static void main(String[] args) { TreeSet<Integer> numbers = new TreeSet<>(); numbers.add(10); numbers.add(20); numbers.add(5); for (int number : numbers) { System.out.println(number); } } }

Output

5 10 20
This code creates a TreeSet named numbers that stores integers. As Integer implements Comparable, elements are sorted in their natural order (ascending order for integers).
3. Custom Objects with Natural Ordering:
Treeset example with custom object import java.util.TreeSet; class Person implements Comparable<Person> { String name; int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override public int compareTo(Person other) { return this.name.compareTo(other.name); // Sort by name } } public class Main { public static void main(String[] args) { TreeSet<Person> people = new TreeSet<>(); people.add(new Person("Sathish", 30)); people.add(new Person("Mohammed", 25)); people.add(new Person("Charlie", 35)); for (Person person : people) { System.out.println("Name: " + person.name + ", Age: " + person.age); } } }

Output

Name: Charlie, Age: 35 Name: Mohammed, Age: 25 Name: Sathish, Age: 30
This code defines a custom class Person with name and age attributes. It also implements the Comparable interface and overrides the compareTo method to define how objects are compared within the TreeSet. Here, elements are sorted by name.
4. Custom Objects with Comparator:
Treeset example with custom object and comparator import java.util.*; class Product { int id; String name; double price; public Product(int id, String name, double price) { this.id = id; this.name = name; this.price = price; } } public class Main { public static void main(String[] args) { Comparator<Product> comparator = new Comparator<Product>() { @Override public int compare(Product p1, Product p2) { return Double.compare(p1.price, p2.price); // Sort by price } }; TreeSet<Product> products = new TreeSet<>(comparator); products.add(new Product(1, "Graphics card", 599.99)); products.add(new Product(2, "Ram", 79.95)); products.add(new Product(3, "Keyboard", 199.99)); for (Product product : products) { System.out.println("ID: " + product.id + ", Name: " + product.name + ", Price: $" + product.price); } } }

Output

ID: 2, Name: Ram, Price: $79.95 ID: 3, Name: Keyboard, Price: $199.99 ID: 1, Name: Graphics card, Price: $599.99
This code defines a custom class Product and a custom comparator. The comparator sorts Product objects based on their price.
Remember, for TreeSet to work with custom objects, they must either implement Comparable or you need to provide a custom comparator during creation to define the sorting criteria.

Tutorials